package com.stateflow.facade.common.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by weiqingming on 2017/8/11.
 * HTTP请求工具
 */
public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    private static final String CHARSET = "UTF-8";
    private static final String CONTENT_TYPE = "application/json";
    private static final RequestConfig REQUEST_CONFIG =
                         RequestConfig.custom().
                         setSocketTimeout(5000).
                         setConnectTimeout(5000).
                         setConnectionRequestTimeout(5000).build();

    /**
     * 发送POST请求，无参数
     * @param httpUrl 地址
     */
    public static String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);
        return sendHttpPost(httpPost);
    }

    /**
     * 发送POST请求
     * @param httpUrl 地址
     * @param params  参数
     */
    public static String sendHttpPost(String httpUrl, String params) {
        return sendHttpPost(getHttpPost(httpUrl, params));
    }

    /**
     * 发送POST请求(HTTPS)
     * @param httpUrl 地址
     * @param params  参数
     */
    public static String sendHttpsPost(String httpUrl, String params) {
        return sendHttpsPost(getHttpPost(httpUrl, params));
    }

    /**
     * 发送POST请求
     * @param httpUrl 地址
     * @param maps    参数
     */
    public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送GET请求
     * @param httpUrl
     */
    public static String sendHttpGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet);
    }

    /**
     * 发送GET请求(HTTPS)
     * @param httpUrl
     */
    public static String sendHttpsGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpsGet(httpGet);
    }


    /**
     * 发送POST请求
     * @param httpPost
     * @return
     */
    private static String sendHttpPost(HttpPost httpPost) {

        CloseableHttpResponse response = null;
        String responseContent = null;
        CloseableHttpClient httpClient = null;

        try {

            // 创建默认的httpClient实例.
            httpClient = getHttpClient();
            httpPost.setConfig(REQUEST_CONFIG);

            // 执行请求
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String charset = CHARSET;
            responseContent = EntityUtils.toString(entity, charset);

        } catch (Exception e) {

            LOGGER.error("Exception:", e);

        } finally {

            releaseResources(response, httpClient);
        }
        return responseContent;
    }

    /**
     * 发送POST请求(HTTPS)
     * @param httpPost
     * @return
     */
    private static String sendHttpsPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseContent = null;

        try {

            // 创建默认的httpClient实例.
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpPost.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpPost.setConfig(REQUEST_CONFIG);

            // 执行请求
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String charset = CHARSET;
            responseContent = EntityUtils.toString(entity, charset);

        } catch (Exception e) {

            LOGGER.error("Exception:", e);

        } finally {
            releaseResources(response, httpClient);
        }
        return responseContent;
    }

    /**
     * 发送GET请求
     * @param httpGet
     * @return
     */
    private static String sendHttpGet(HttpGet httpGet) {
        ;
        CloseableHttpResponse response = null;
        String responseContent = null;
        CloseableHttpClient httpClient = null;

        try {

            // 创建默认的httpClient实例.
            httpClient = getHttpClient();
            httpGet.setConfig(REQUEST_CONFIG);

            // 执行请求
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, CHARSET);

        } catch (Exception e) {

            LOGGER.error("Exception:", e);

        } finally {

            releaseResources(response, httpClient);
        }

        return responseContent;
    }

    /**
     * 发送GET请求(HTTPS)
     * @param httpGet
     * @return
     */
    private static String sendHttpsGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseContent = null;

        try {

            // 创建默认的httpClient实例.
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(REQUEST_CONFIG);

            // 执行请求
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, CHARSET);

        } catch (Exception e) {

            LOGGER.error("Exception:", e);

        } finally {
            releaseResources(response, httpClient);
        }
        return responseContent;
    }

    /**
     * 释放资源
     * @param response
     * @param httpClient
     */
    private static void releaseResources(CloseableHttpResponse response, CloseableHttpClient httpClient) {

        // 关闭连接,释放资源
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                LOGGER.error("释放资源失败", e);
            }
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                LOGGER.error("释放资源失败", e);
            }
        }
    }

    /**
     * 获取HttpPost
     * @param httpUrl
     * @param params
     * @return
     */
    private static HttpPost getHttpPost(String httpUrl, String params) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            // 设置参数
            StringEntity stringEntity = new StringEntity(params, CHARSET);
            stringEntity.setContentType(CONTENT_TYPE);
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            LOGGER.error("获取HttpPost失败", e);
        }
        return httpPost;
    }

    /**
     * 获取HTTP连接客户端
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

}
